//
//  NSObject+NBL.m
//  NBLiOSTools
//
//  Created by GangX-yangjh on 2021/12/5.
//

#import "NSObject+NBL.h"
#import <objc/runtime.h>

@implementation NSObject (NBL)

// 对象转字典
- (NSDictionary *)toDictionary
{
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
    // 获得属性列表
    unsigned int propsCount;
    objc_property_t *props = class_copyPropertyList([self class], &propsCount);
    // 遍历属性
    for (int i = 0; i < propsCount; i++) {
        // 获得属性的名称
        objc_property_t prop = props[i];
        NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
        // 通过kvc读值
        id value = [self valueForKey:propName];
        if (value == nil) {
            value = [NSNull null];
        } else {
            // 自定义处理数组、字典、基本类
            value = [value getObjectInternal];
        }
        mdic[propName] = value;
    }
    return mdic;
}
- (id)getObjectInternal
{
    if ([self isKindOfClass:[NSString class]] ||
        [self isKindOfClass:[NSNumber class]] ||
        [self isKindOfClass:[NSNull class]]) {
        return self;
    }
    if ([self isKindOfClass:[NSArray class]]) {
        NSArray *objarr = (NSArray *)self;
        NSMutableArray *marr = [NSMutableArray array];
        for(int i = 0; i < objarr.count; i++) {
            marr[i] = [objarr[i] getObjectInternal];
        }
        return marr;
    }
    if ([self isKindOfClass:[NSDictionary class]]) {
        NSDictionary *objdic = (NSDictionary *)self;
        NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
        for (NSString *key in objdic.allKeys){
            mdic[key] = [objdic[key] getObjectInternal];
        }
        return mdic;
    }
    return [self toDictionary];
}

@end
